package com.lanou.dllo.findfood.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.lanou.dllo.findfood.entity.HomeTopDeals;
import com.lanou.dllo.findfood.util.Constant;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dllo on 15/10/31.
 */
public class MySQLiteDataBaseUtil {
    private SQLiteDatabase database;

    public MySQLiteDataBaseUtil(Context context) {
        init(context);
    }

    private void init(Context context) {
//factory 游标, version
        //构建数据库帮助类用于数据库对象的获取
        //参数二表示数据库名
        MySQLiteOpenHelper helper = new MySQLiteOpenHelper(context, Constant.DATABASE_NAME, null, 3);
        database = helper.getWritableDatabase();
    }

    //以键值对的形式保存
    public void savaHomeViewPager(List<HomeTopDeals> dealsList) {
        for (HomeTopDeals homeTopDeals : dealsList) {
            ContentValues values = new ContentValues();
            values.put(Constant.COLUMN_HOME_VIEWPAGER_DEAL_ID, homeTopDeals.getDeal_id());
            values.put(Constant.COLUMN_HOME_VIEWPAGER_IMAGE, homeTopDeals.getImage());
            values.put(Constant.COLUMN_HOME_VIEWPAGER_TITLE, homeTopDeals.getTitle());
            values.put(Constant.COLUMN_HOME_VIEWPAGER_DESCRIPTION,homeTopDeals.getDescription());
            database.insert(Constant.TABLE_NAME_HOME_VIEWPAGER, null, values);


        }
    }

    public void deleHomeViewpager() {
        database.delete(Constant.TABLE_NAME_HOME_VIEWPAGER, null, null);
    }

    public List<HomeTopDeals> queryHomeViewPageData() {

        Cursor cursor = database.query(Constant.TABLE_NAME_HOME_VIEWPAGER, null,
                null, null, null, null, null);
        if (cursor != null) {
            List<HomeTopDeals> dealses = new ArrayList<HomeTopDeals>();
            while (cursor.moveToNext()) {
                String image = cursor.getString(cursor.getColumnIndex(Constant.COLUMN_HOME_VIEWPAGER_IMAGE));
                int deal_id = cursor.getInt(cursor.getColumnIndex(Constant.COLUMN_HOME_VIEWPAGER_DEAL_ID));
                String title = cursor.getString(cursor.getColumnIndex(Constant.COLUMN_HOME_VIEWPAGER_TITLE));
                String description =cursor.getString(cursor.getColumnIndex(Constant.COLUMN_HOME_VIEWPAGER_DESCRIPTION));
                HomeTopDeals deals = new HomeTopDeals();
                deals.setDeal_id(deal_id);
                deals.setDescription(description);
                deals.setTitle(title);
                deals.setImage(image);
                dealses.add(deals);
            }
            cursor.close();
            return dealses;
        }


        return null;
    }




}
